'''
import ResolveWar3 
import ctypes
import os

# dllInit
stormdll = ctypes.WinDLL('E:\\VScode_project\\python work\\StormLib_x64.dll')

# Readfun
SFileOpenFileEx = stormdll.SFileOpenFileEx
SFileGetFileSize = stormdll.SFileGetFileSize
SFileSetFilePointer = stormdll.SFileSetFilePointer
SFileReadFile = stormdll.SFileReadFile
SFileCloseFile = stormdll.SFileCloseFile
SFileHasFile = stormdll.SFileHasFile
SFileGetFileName = stormdll.SFileGetFileName
SFileGetFileInfo = stormdll.SFileGetFileInfo
SFileVerifyFile = stormdll.SFileVerifyFile
SFileVerifyArchive = stormdll.SFileVerifyArchive
SFileExtractFile = stormdll.SFileExtractFile

class UnpackMQP():
    pass

'''
# 上面的先不做了！

import ResolveWar3
import os
import math

w2lPath = 'w3x2lni\\w2l.exe'
cachePath = 'cache'
ExportPath = ''

def WriteJassCode(obj):
    if 'doodads' in obj:
        code = "function Create_doodad0 takes nothing returns nothing\n"
        func_number = 1
        rows = 1
        for doodad in obj['doodads']:
            if doodad['生命'] > 0:
                code += "call CreateDestructableZ('%s',%.2f,%.2f,%.2f,%.2f,%.3f,%s)\n" % (doodad['ID'],doodad['位置 X'],doodad['位置 Y'],doodad['位置 Z'],math.degrees(doodad['面向角度']),doodad['缩放 X'],doodad['样式'])
                rows += 1
                if rows >= 20000:
                    rows = 0
                    code += 'endfunction\n'
                    code += "function Create_doodad%s takes nothing returns nothing\n" % (func_number)
                    func_number +=1
        code += 'endfunction\n'
        code += "function Create_doodad takes nothing returns nothing\n"
        code += "local timer ys_timer\n"
        for number in range(func_number):
            code += "set ys_timer = CreateTimer()\n"
            code += "call TimerStart(ys_timer,%1f,false, function Create_doodad%s)\n" % (10+number,number)
        code += 'set ys_timer = null\n'
        code += 'endfunction\n'
    elif 'units' in obj:
        code = 'local unit u'
        for unit in obj['units']:
            code += "set u = CreateUnit(Player(%s),%s,%.2f,%.2f,%.2f)\n" % (unit['玩家'],unit['ID'],unit['位置 X'],unit['位置 Y'],unit['面向角度'])
    elif 'magic_number' in obj and obj['magic_number'] == 'W3E!':
        code = "function Create_w3e0 takes nothing returns nothing\n"
        func_number = 1
        rows = 1
        layer = 2
        for Y in range(obj['地图高度']):
            for X in range(obj['地图宽度']):
                tile = obj['tiles'].pop(0)
                coordinate_X = X*128 + obj['地图水平偏移']
                coordinate_Y = Y*128 + obj['地图垂直偏移']
                code += "call TerrainDeformCrater(%.2f,%.2f,128,-%.2f,1,true)\n" % (coordinate_X,coordinate_Y,(tile['地面高度'] - 8192 + (layer - 2) * 512) / 4)
                code += "call SetTerrainType(%.2f,%.2f,'%s',%s,1,1)\n" % (coordinate_X,coordinate_Y,obj['使用地面纹理'][tile['地面纹理']],tile['纹理变化'])
                rows += 2
                if rows >= 20000:
                    rows = 0
                    code += 'endfunction\n'
                    code += "function Create_w3e%s takes nothing returns nothing\n" % (func_number)
                    func_number +=1
        code += 'endfunction\n'
        code += "function Create_w3e takes nothing returns nothing\n"
        code += "local timer ys_timer\n"
        for number in range(func_number):
            code += "set ys_timer = CreateTimer()\n"
            code += "call TimerStart(ys_timer,%1f,false, function Create_w3e%s)\n" % (number * 2,number)
        code += 'set ys_timer = null\n'
        code += 'endfunction\n'
    else:
        return False
    return code

def WriteObjDocument(obj):
    def Traversaldict(backspace_numbe):
        def Traversaldict0(obj):
            text = ''
            if type(obj) == dict:
                for key in obj:
                    value = obj[key]
                    if type(value) == dict or type(value) == list:
                        CU = Traversaldict(backspace_numbe + 1)
                        text += CU(value)
                    else:
                        text += '\n' + '\t' * backspace_numbe + '%s : %s' % (key,value)
            elif type(obj) == list:
                for value in obj:
                    if type(value) == dict or type(value) == list:
                        CU = Traversaldict(backspace_numbe + 1)
                        text += CU(value)
                    else:
                        text += '\n' + '\t' * backspace_numbe + '%s' % (value)
            return text
        return Traversaldict0
    if 'doodads' in obj:
        coust = obj['doodads_count']
        if coust > 0:
            text = '可破坏物数量 : %s' % (coust)
            for doodad in obj['doodads']:
                CU = Traversaldict(0)
                text += CU(doodad) + '\n'
        else:
            return False

    elif 'units' in obj:
        coust = obj['unit_count']
        if coust > 0:
            text = '单位数量 : %s' % (obj['unit_count'])
            for unit in obj['units']:
                CU = Traversaldict(0)
                text += CU(unit) + '\n'
        else:
            return False
    elif 'magic_number' in obj and obj['magic_number'] == 'W3E!':
        CU = Traversaldict(0)
        text = '主地面纹理类型 : %s' % (obj['主地面纹理类型'])
        text += '\n' + '使用自定义地面纹理组合 : %s' % (obj['使用自定义地面纹理组合'])
        text += '\n' + '使用地面纹理数量 : %s' % (obj['使用地面纹理数量'])
        text += '\n' + '使用的地面纹理 :' + CU(obj['使用地面纹理'])
        text += '\n' + '使用悬崖纹理数量 : %s' % (obj['使用悬崖纹理数量'])
        text += '\n' + '使用的悬崖纹理 :' + CU(obj['使用悬崖纹理'])
        text += '\n' + '地图宽度 : %s' % (obj['地图宽度'])
        text += '\n' + '地图高度 : %s' % (obj['地图高度'])
        text += '\n' + '地图水平偏移 : %s' % (obj['地图水平偏移'])
        text += '\n' + '地图垂直偏移 : %s' % (obj['地图垂直偏移'])
        for tiles_number in range(len(obj['tiles'])):
            text += '\n\n%s' % (tiles_number)
            text += CU(obj['tiles'][tiles_number])
    elif 'regions' in obj:
        coust = obj['regions_coust']
        if coust > 0:
            text = '矩形区域数量 : %s' % (coust)
            for region in obj['regions']:
                CU = Traversaldict(0)
                text += CU(region) + '\n'
        else:
            return False
    else:
        print(obj)
        return False
        
    return text

def CreatePreinstall(mapPath,mode):

    for root, _, files in os.walk(mapPath):
        for file in files:
            filepath = root + '\\' + file
            if file.lower() == 'war3map.doo':
                with open(filepath,'rb') as f:
                    doodad_obj = ResolveWar3.UnpackDoodad_doo(f.read())
            elif file.lower() == 'war3mapunits.doo':
                with open(filepath,'rb') as f:
                    unit_obj = ResolveWar3.UnpackUnit_doo(f.read())
            elif file.lower() == 'war3map.w3e':
                with open(filepath,'rb') as f:
                    w3e_obj = ResolveWar3.UnpackW3e(f.read())
            elif file.lower() == 'war3map.w3r':
                with open(filepath,'rb') as f:
                    w3r_obj = ResolveWar3.UnpackW3r(f.read())
    
    if mode == 0:
        doodad_text = WriteObjDocument(doodad_obj)
        unit_text = WriteObjDocument(unit_obj)
        w3e_text = WriteObjDocument(w3e_obj)
        w3r_text = WriteObjDocument(w3r_obj)

        if doodad_text :
            with open(ExportPath + '\\' + 'doodand_preinstall.txt','w') as f:
                f.write(doodad_text)
        if unit_text :
            with open(ExportPath + '\\' + 'unit_preinstall.txt','w') as f:
                f.write(unit_text)
        if w3e_text :
            with open(ExportPath + '\\' + 'w3e_preinstall.txt','w') as f:
                f.write(w3e_text)
        if w3r_text :
            with open(ExportPath + '\\' + 'w3r_preinstall.txt','w') as f:
                f.write(w3r_text)
    elif mode == 1:
        doodad_code = WriteJassCode(doodad_obj)
        w3e_code = WriteJassCode(w3e_obj)
        if doodad_code :
            with open(ExportPath + '\\' + 'doodad_code.j','w') as f:
                f.write(doodad_code)
        # if unit_text :
        #     with open(ExportPath + '\\' + 'unit_preinstall.txt','w') as f:
        #         f.write(unit_text)
        if w3e_code :
            with open(ExportPath + '\\' + 'w3e_code.j','w') as f:
                f.write(w3e_code)
        # if w3r_text :
        #     with open(ExportPath + '\\' + 'w3r_preinstall.txt','w') as f:
        #         f.write(w3r_text)

def main():
    global ExportPath
    print('该工具是用以导出地图内预设信息的(地形信息,预设可破坏物,预设单位,预设矩形区域等)\n生成的文件在地图目录下\n可以将地图文件拖入到cmd窗口内获得路径\n\t注:矩形区域不能用中文命名不然会报错\n\t   360会日常报毒\n' + '作者:欲死\n')
    while True:
        if not os.path.exists(w2lPath):
            print("没有找到w3x2lni文件,请检查是否正确下载w3x2lni")
            os.system('pause')
            return
        mapPath = input('请填入地图路径并按回车确认 : \n')
        if not mapPath[len(mapPath)-4:] == '.w3x':
            print("错误的文件格式,请重新输入")
            continue
        mapPath = os.path.abspath(mapPath)
        ExportPath = os.path.dirname(mapPath)
        os.system(w2lPath + ' lni ' + mapPath + ' ' + cachePath)
        while True:
            method = input('选择导出类型 : \n\t0 : txt\t1 : jass\n')
            if method in ['0','1']:
                break
        CreatePreinstall(cachePath + '\\map',int(method))
        print("导出结束\n")
main()

# def test():
#     global ExportPath
#     global w2lPath
#     w2lPath = "E:\\Work_War3\\War3MoeHero\\MoeHero-master\\w3x2lni_zhCN_v2.5.2\\w2l.exe"
#     ExportPath = 'F:\\WorldEdit v1.2.9a\\WorldEdit v1.2.9a\\WorldEdit v1.2.9a\\jass'
#     mapPath = 'C:\\Users\\Administrator\\Desktop\\W3ETEST.w3x'
#     os.system(w2lPath + ' lni ' + mapPath + ' ' + cachePath)
#     CreatePreinstall(cachePath + '\\map',1)

# test()